# -*- coding:Utf-8 -*-
'''
Created on 25 nov. 2012

@author: fefoley
'''

import ConfigParser
from datetime import datetime
from codecs import decode
from pyicl import Interval, IntervalSet, IntervalMap, IntervalBounds, IntervalStringMap

from proofs import Mail, Meeting, SentMeeting
from divers import Str2sum


def import_config(path_to_configfile):
    """
    Import the config file in a dictionary for latter use
    return config  typeof(dictionary)
    """
    parser = ConfigParser.ConfigParser()
    parser.read(path_to_configfile)
    return parser    


def import_mails(config):
    """    importer la liste des mails - décodage des lignes à faire par l'object Mail    """
    'read confil file to know where are the mail files'
    root_path = config.get('inputfiles','rootpath')
    file_paths = config.get('inputfiles','mails').split('\n')
    
    'read config file for setup variables : up/down time'
    setup = int(config.get('setuptime','mailstart'))
    setdown  = int(config.get('setuptime','mailend'))
    adh = int(config.get('setuptime','mailadherence'))
    
    'go through the files'
    lstmails = []
    for p in file_paths:
        f = open(root_path + p, 'r')
        f.readline() #ignore head lines
        for line in f:
            dline = decode(line, 'cp1252')    #depend on vba output
            mail = Mail(dline)                # lecture des lignes à faire par l'object
            mail.set_setup(setup, setdown, adh)
            lstmails.append(mail)   
        f.close()
    return lstmails

def import_sentmeetings(config):
    """    importer la liste des réunions - décodage des lignes à faire par l'object SentMeeting."""
    'read confil file to know where are the sentmeetings files'
    root_path = config.get('inputfiles','rootpath') 
    file_paths = config.get('inputfiles','meetings').split('\n')

    'read config file for setup variables : up/down time'
    setup = int(config.get('setuptime','sentmeetingstart'))
    setdown  = int(config.get('setuptime','sentmeetingend'))
    adh = int(config.get('setuptime','sentmeetingadherence'))
        
    'read config file for sender keywords'
    me = config.get('self','name')
    
    'go through the files'    
    lstsentmeetings = []
    for p in file_paths:
        f = open(root_path + p, 'r')
        f.readline() #ignore head lines   
        for line in f:
            dline = decode(line, 'cp1252')
            sentmeeting = SentMeeting(dline)
            ' check if I sent it before adding it to the list'         
            if me.lower() in sentmeeting.getsender().lower() :
                sentmeeting.set_setup(setup, setdown, adh)
                lstsentmeetings.append(sentmeeting) 
        f.close()
    return lstsentmeetings


def import_meetings(config):
    """    importer la liste des réunions - décodage des lignes à faire par l'object Meeting    """
    'read confil file to know where are the meetings files'
    root_path = config.get('inputfiles','rootpath')  
    file_paths = config.get('inputfiles','meetings').split('\n')

    'read config file for setup variables : up/down time'
    setup = int(config.get('setuptime','meetingstart'))
    setdown  = int(config.get('setuptime','meetingend'))
    adh = int(config.get('setuptime','meetingadherence'))    
    
    'go through the files'    
    lstmeetings = []
    for p in file_paths:
        f = open(root_path + p, 'r')
        f.readline() #ignore head lines   
        for line in f:
            dline = decode(line, 'cp1252')   
            meeting = Meeting(dline)                # lecture des lignes à faire par l'object
            meeting.set_setup(setup, setdown, adh)                     
            lstmeetings.append(meeting) 
        f.close()
    return lstmeetings


def import_holidays(config):
    """importer la liste des jours fériés
    import csv with holyday listing assuming the following structure: 
    Date(dd/mm/yyyy)  String(nom du jour férié)
    return list of (datetime.date, strNomJourFerie)
    """ 
    'read confil file to know where are the import_holidays files'
    root_path = config.get('inputfiles','rootpath')  
    file_paths = config.get('inputfiles','holidays').split('\n')

    'go through the files'          
    lstholidays = []
    for p in file_paths:    
        f = open(root_path + p, 'r')
        f.readline() #ignore head lines
        for line in f:
            linesplit = line.rstrip('\n').split('\t')  # take off endofline - date+nomjourférié per line
            if len(linesplit) != 2:   # should be 2 fields
                raise Exception("format error for {}".format(linesplit))  # could be some formatting errors
            else:
                lstholidays.append((datetime.datetime.strptime(linesplit[0], "%d/%m/%Y").date(), linesplit[1]))
        f.close()                   
    return lstholidays

def import_holidays2(config):
    """importer la liste des jours fériés
    import csv with holyday listing assuming the following structure: 
    Date(dd/mm/yyyy)  String(holiday name)
    return list IntervalMap of the holidays (date, name)
    """     
    
    'read confil file to know where are the import_holidays files'
    root_path = config.get('inputfiles','rootpath')  
    file_paths = config.get('inputfiles','holidays').split('\n')
    
    'go through the files'          
#    holidays = IntervalMap()
    holidays = IntervalStringMap()
    for p in file_paths:    
        f = open(root_path + p, 'r')
        f.readline() #ignore head lines
        for line in f:
            linesplit = line.rstrip('\n').rstrip('\r').split('\t')  # take off endofline - date+nomjourférié per line
            if len(linesplit) != 2:   # should be 2 fields
                raise Exception("format error for {}".format(linesplit))  # could be some formatting errors
            else:
                dateholiday = datetime.strptime(linesplit[0], "%d/%m/%Y").date()
#                holidays = holidays.add(IntervalMap.Segment(Interval(dateholiday), Str2sum(linesplit[1])))
                holidays = holidays.add(IntervalStringMap.Segment(Interval(dateholiday), linesplit[1]))
        f.close()       
    return holidays

def import_daysoff2(config):
    """
    import csv with dayoff listing
    assuming the following structure: 
    FromDate(dd/mm/yyyy) ToIncludedDate(dd/mm/yyyy) TypeOfDayoff(string) NbOfDayoff(float) 
    return IntervalMap ([date, date], type)
    """
    'read confil file to know where are the import_daysoff files'
    root_path = config.get('inputfiles','rootpath')  
    file_paths = config.get('inputfiles','dayoffs').split('\n')
        
#    dayoffs_map = IntervalMap()
    dayoffs_map = IntervalStringMap()
    for p in file_paths:      
        f = open(root_path + p, 'r')
        f.readline() #ignore head lines
        for line in f:
            linesplit = line.rstrip('\n').split('\t')  # take off endofline and split with TAB
            if len(linesplit) != 4:   # should be 4 fields
                raise Exception("format error for {}".format(linesplit))  # could be some formatting errors
            else:
                strFromDate, strToDate, strType, _ = linesplit
                start_date = datetime.strptime(strFromDate, "%d/%m/%Y").date()
                end_date = datetime.strptime(strToDate, "%d/%m/%Y").date()
#                dayoffs_map = dayoffs_map.add(IntervalMap.Segment(Interval(start_date, 
#                                                                           end_date, 
#                                                                           IntervalBounds.CLOSED), 
#                                                                  Str2sum(strType)))
                dayoffs_map = dayoffs_map.add(IntervalStringMap.Segment(Interval(start_date, 
                                                                           end_date, 
                                                                           IntervalBounds.CLOSED), 
                                                                  strType))
        f.close()
    return dayoffs_map    

def import_daysoff(config):
    """
    import csv with dayoff listing
    assuming the following structure: 
    FromDate(dd/mm/yyyy) ToIncludedDate(dd/mm/yyyy) TypeOfDayoff(string) NbOfDayoff(float) 
    return list of (date, date, type, nb)
    """
    'read confil file to know where are the import_daysoff files'
    root_path = config.get('inputfiles','rootpath')  
    file_paths = config.get('inputfiles','dayoffs').split('\n')
        
    lstdayoffs = []
    for p in file_paths:      
        f = open(root_path + p, 'r')
        f.readline() #ignore head lines
        for line in f:
            linesplit = line.rstrip('\n').split('\t')  # take off endofline and split with TAB
            if len(linesplit) != 4:   # should be 4 fields
                raise Exception("format error for {}".format(linesplit))  # could be some formatting errors
            else:
                strFromDate, strToDate, strType, strNb = linesplit
                lstdayoffs.append((datetime.datetime.strptime(strFromDate, "%d/%m/%Y").date(), \
                                  datetime.datetime.strptime(strToDate, "%d/%m/%Y").date(), \
                                  strType, float(strNb)))
        f.close()
    return lstdayoffs    


def debug_output(debug_str, config):
    'read confil file to know where to output'
    root_path = config.get('outputfiles','rootpath')  
    file_path = config.get('outputfiles','debug')
    path = root_path + file_path
    f = open(path, 'w')
    f.write(debug_str)
    f.close
    
        
def output_timestrip(lst_lst_timestrip, config): 
    """
    YYYY/MM/DD    tsStart    tsEnd    encoded_Label
    """     
    'read confil file to know where to output'
    root_path = config.get('outputfiles','rootpath')  
    file_path = config.get('outputfiles','timestrip')
    path = root_path + file_path
    f = open(path, 'w')
    
    for lst_timestrip in lst_lst_timestrip:
        for ts in lst_timestrip:
            line = (ts.start.strftime("%Y/%m/%d") +
                        '\t' + ts.start.strftime("%H:%M") +
                        '\t' + ts.end.strftime("%H:%M") +
                        '\t' + ts.label.replace('\t','\\utab').replace('\n','\\ueol') +
                        '\n')
            f.write(line)
    
    f.close      
    
def import_scope(config):
    """Function to read the scope : starting and ending day.   """
    str_start = config.get('workday','startday')
    str_end = config.get('workday','endday')
    start = datetime.strptime(str_start, "%d/%m/%Y").date()
    end = datetime.strptime(str_end, "%d/%m/%Y").date()

    return Interval(start, end, IntervalBounds.CLOSED)


